package eudjok
import twitter4j.Status
import twitter4j.Twitter
import twitter4j.TwitterException
import twitter4j.TwitterFactory
import twitter4j.http.AccessToken
import twitter4j.http.RequestToken
import twitter4j.User


class LoginController {
	
	String consumerKey = "94l4la4Ews1sFTDwWxCTKQ"
	String secretKey = "jfM506MvlpzYEqalaQmUjdsFOECk6E3OfaGDVTgAw"
	String callBack = "http://localhost:8080/eudjok/login/validando"
	
	def index = { 
		redirect(action: "login", params: params)
	}
	
	def login = {
		try{

			Twitter twitter = new TwitterFactory().getInstance()
			twitter.setOAuthConsumer(consumerKey, secretKey)
			RequestToken requestToken = twitter.getOAuthRequestToken(callBack)
			flash.pagina = requestToken.getAuthorizationURL()
			
			session.requestToken = requestToken
		
		}
		catch(TwitterException te){
			flash.pagina = "erro"
		}
		
		
	
	}
	
	def validando = {
		
		String pin = params.oauth_verifier
		
		if(pin == "401"){
			redirect(action: "login", params: params)
		}
		
		Twitter twitter = new TwitterFactory().getInstance()
		twitter.setOAuthConsumer(consumerKey, secretKey)
		
		
		RequestToken requestToken = session.requestToken
		
		AccessToken accessToken = null;
		
		accessToken = twitter.getOAuthAccessToken(requestToken, pin)
		
		session.twitter = twitter
		
		session.autenticado = accessToken
		
		User usuario = twitter.showUser(twitter.getScreenName())
		
		session.userT = usuario
		
		def dj = Dj.findByTwitter(usuario.getId())
		
		if(dj){
			session.dj = dj
			redirect(controller:'home',action:'index')
		}
		else{
			redirect(controller:'dj',action:'create')
		}
	
	}

}